package com.woniu.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname GlobalException
 * @Description 专门处理异常的类
 * @Date 2025/8/6 14:19
 * @Created by pc
 */
@ControllerAdvice("com.woniu.controller")
public class GlobalException {

    // 在springmvc中 servlet api 可以直接作为入参 session request response
    @ExceptionHandler(Throwable.class)
    public void handlerException(Throwable e, HttpServletResponse response){
        e.printStackTrace();
        Map<String,Object> map = new HashMap<>();
        map.put("code",500);
        map.put("msg","系统异常，请联系管理员");
        // 前后台传输的是json格式数据
        // response.setCharacterEncoding("UTF-8");
        // 以前我们使用response 向前台输出数据 文本形式 text/html;charset=utf-8
        response.setContentType("application/json;charset=utf-8"); //  application/json;charset=utf-8
        try {
            // json字符串 "{k:v,k:v}"
            ObjectMapper objectMapper = new ObjectMapper(); // jackson 包中的类，这个类可以将对象转换成json字符串
            String s = objectMapper.writeValueAsString(map);
            response.getWriter().write(s);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

    }
}
